<?php
/**
 * @copyright Copyright (c) 2022 勾股工作室
 * @license https://opensource.org/licenses/GPL-3.0
 * @link https://www.gougucms.com
 */
declare (strict_types = 1);
namespace app\finance\controller;

use app\api\BaseController;
use app\finance\model\Expense;
use app\finance\model\Invoice;
use app\finance\model\InvoiceIncome;
use think\facade\Db;
use think\facade\View;

class Api extends BaseController
{
    //删除报销附件
    public function del_expense_interfix()
    {
        $id = get_params("id");
//        $admin_id = Db::name('ExpenseInterfix')->where('id', $id)->value('admin_id');
//        if ($admin_id == $this->uid) {
            if (Db::name('ExpenseInterfix')->where('id', $id)->delete() !== false) {
                return to_assign(0, "删除成功");
            } else {
                return to_assign(1, "删除失败");
            }
//        } else {
//            return to_assign(1, "您不是上传者，没权限删除该报销数据");
//        }
    }
	
	//报销设置为已打款
    public function topay()
    {
        $param = get_params();
        if (request()->isAjax()) {
//			$auth = isAuthExpense($this->uid);
//			if($auth == 0){
//				return to_assign(1, "你没有打款权限，请联系管理员或者HR");
//			}
            $auth=check_auth('finance/api/topay',$this->uid);
            if (!$auth){
                return to_assign(1, "你没有打款权限，请联系管理员或者HR");
            }
			//打款，数据操作
            $param['check_status'] = 5;
            $param['pay_admin_id'] = $this->uid;
            $param['pay_time'] = time();
            $info=Expense::where('id',$param['id'])->find()->toArray();
            $money=Db::name('expense_interfix')->where('exid',$param['id'])->sum('amount');
            Db::startTrans();
            try {
                Expense::where('id', $param['id'])->strict(false)->field(true)->update($param);
                add_log('topay', $param['id'],$param,'报销');
                //金额变动记录
                $recordData=[
                    'orderDate'=>date('Y-m-d'),
                    'relatedOrderNum'=>$info['orderNum'],
                    'uid'=>$info['admin_id'],
                    'money'=>$money?$money:0,
                    'orderType'=>5,

                ];
                moneyRecord($recordData);
                //发送消息通知
                $detail = Expense::where(['id' => $param['id']])->find();
                $msg=[
                    'create_time'=>$detail['create_time'],
                    'title'=>'报销',
                    'action_id'=>$detail['id']
                ];
                $users = $detail['admin_id'];
                sendMessage($users,34,$msg);
                Db::commit();
            }catch ( \Exception $e){
                Db::rollback();
                return to_assign(1, "操作失败:".$e->getMessage());
            }
            return to_assign();
//            if ($res !== false) {
//
//                return to_assign();
//            } else {
//                return to_assign(1, "操作失败");
//            }
        }
    }
	
    //开具发票
    public function open()
    {
        $param = get_params();
        if (request()->isAjax()) {
//			$auth = isAuthInvoice($this->uid);
//			if($auth == 0){
//				return to_assign(1, "你没有开票权限，请联系管理员或者HR");
//			}
//            if (!check_auth('finance/BuyInvoice/open',$this->uid)){
//                return to_assign(1, "你没有开票权限，请联系管理员或者HR");
//            }
//            if (!check_auth('finance/api/open',$this->uid)){
//                return to_assign(1, "你没有开票权限，请联系管理员或者HR");
//            }
			$status = Invoice::where(['id' => $param['id']])->value('check_status');
            if ($status == 2) {
                $param['check_status'] = 5;
                $param['open_admin_id'] = $this->uid;
            }
			if(isset($param['open_time'])){
				$param['open_time'] = strtotime(urldecode($param['open_time']));
			}
            $res = Invoice::where('id', $param['id'])->strict(false)->field('code,check_status,open_time,open_admin_id,delivery,other_file_ids')->update($param);
            if ($res !== false) {
				add_log('open', $param['id'],$param,'发票');
                return to_assign();
            } else {
                return to_assign(1, "操作失败");
            }
        }
    }
	
    //作废发票
    public function tovoid()
    {
        $param = get_params();
        if (request()->isAjax()) {
			$auth = isAuthInvoice($this->uid);
			if($auth == 0){
				return to_assign(1, "你没有作废发票权限，请联系管理员或者HR");
			}
            if ($param['check_status'] == 10) {
                $count = InvoiceIncome::where(['inid'=>$param['id'],'status'=>1])->count();
                if($count>0){
                    return to_assign(1, "发票已经新增有到账记录，请先反到账后再作废发票");
                }
                else{
                    $param['update_time'] = time();
                }
            }
            $res = Invoice::where('id', $param['id'])->strict(false)->field('check_status')->update($param);
            if ($res !== false) {
                return to_assign();
                add_log('tovoid', $param['id'],$param,'发票');
            } else {
                return to_assign(1, "操作失败");
            }
        }
    }

    //反作废发票
    public function novoid()
    {
        $param = get_params();
        if (request()->isAjax()) {
			$auth = isAuthInvoice($this->uid);
			if($auth == 0){
				return to_assign(1, "你没有作废发票权限，请联系管理员或者HR");
			}
			$param['check_status'] = 5;
			$param['update_time'] = time();
			add_log('tovoid', $param['id'],$param,'发票');
            $res = Invoice::where('id', $param['id'])->strict(false)->field('check_status')->update($param);
            if ($res !== false) {
                return to_assign();
				add_log('novoid', $param['id'],$param,'发票');
            } else {
                return to_assign(1, "操作失败");
            }
        }
    }

    /**
     * @return \json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @autho:xiangzi
     * @auth:true
     * @Date:2024/12/17
     * $type:1销售，2采购
     * 合同
     */
    public function getContractList()
    {
        $param=$this->request->param();
        $type=$param['type']??1;
        $punterId=$param['punterId']??'';
        $moType=$param['moType']??1;
        $isOver=$param['isOver']??0;
        $orderNum=$param['orderNum']??'';
        if ($isOver){
            $where[]=['sc.payStatus','<>',3];
        }else{
            if (!$punterId){
                return to_assign('1','参数缺失');
            }
            $where[]=['sc.punterId','=',$punterId];
        }
        if ($punterId){
            $where[]=['sc.punterId','=',$punterId];
        }
        if ($orderNum){
            $where[]=['sc.orderNum','like','%'.$orderNum.'%'];
        }
        if (isset($param['xsDw'])&&$param['xsDw']){
            $where[]=['d.title','like',"%".$param['xsDw'].'%'];
        }
        $where[]=['sc.type','=',$type];
        $where[]=['sc.status','=',4];
        $list=Db::name('sale_contract')
            ->alias('sc')
            ->leftJoin('department d','d.id=sc.salesUnitId')
            ->where($where)
            ->field("sc.id,sc.orderNum,sc.countMoney,sc.punterId,d.title as dName,
            (select sum(money) from fy_money_order_contract_detail mo where mo.status=2 and type=$moType and mo.contractOrder=sc.orderNum)receiptedMoney")
            ->select()->each(function ($item){
                $item['receiptedMoney']=$item['receiptedMoney']?$item['receiptedMoney']:0;
                $item['unPay']=$item['countMoney']-$item['receiptedMoney'];
                $outList=Db::name('stock_order_detail')
                    ->alias('sod')
                    ->leftJoin('sale_contract_detail scd','scd.id=sod.saleContractDetailId')
                    ->where('sod.status',2)
                    ->where('sod.type',1)
                    ->where('scd.orderId',$item['id'])
                    ->field('sod.num as outNum,scd.bjPrice')->select();
                $outMoney=0;
                foreach ($outList as $v){
                    $outMoney+=$v['outNum']*$v['bjPrice'];
                }
                $item['outMoney']=round($outMoney,2);
                $item['kpMoney']=Db::name('invoice')->where('check_status',5)
                    ->where('delete_time',0)
                    ->where('contract_id',$item['id'])->sum('amount');
                return $item;
            });

        return to_assign(0,'获取成功',$list);

    }

    public function getPunterBuyContract()
    {
        $param=$this->request->param();
        $contractId=$param['contractId']??'';
        if (!$contractId){
            return to_assign(1,'参数有误');
        }

        $conInfo=Db::name('sale_contract')->where('id',$contractId)
            ->field('punterId,saleId')->find();
        $saleNames='';
        if ($conInfo['saleId']){
            $name=Db::name('admin')->where('id','in',$conInfo['saleId'])->where('status',1)
                ->column('name');
            $saleNames=implode(',',$name);
        }
        $conInfo['saleNames']=$saleNames;
        return to_assign(0,'获取成功',$conInfo);
    }

    public function getContractBuyPunter()
    {
        $param=$this->request->param();
        $punterId=$param['punterId']??'';
        if (!$punterId){
            return to_assign(1,'参数有误');
        }
        $list=Db::name('sale_contract')
            ->where('punterId',$punterId)
            ->where('type',1)
            ->where('status',4)
            ->field('id,orderNum')
            ->select();
        return to_assign(0,'获取成功',$list);
    }

    /**
     * @return \json|\think\response\View
     * @throws \think\db\exception\DbException
     * @autho:xiangzi
     * @auth:true
     * @Date:2025/6/12
     * 采购收票单获取合同明细
     */
    public function getContract()
    {
        $param=$this->request->param();
        $type=$param['type']??1;
        if ($this->request->isPost()){
            $where[]=['scd.type','=',$type];
            $where[]=['scd.status','=',4];
            if (isset($param['htOrderNum'])&&$param['htOrderNum']){
                $where[]=['sc.orderNum','like','%'.$param['htOrderNum'].'%'];
            }
            if (isset($param['pName'])&&$param['pName']){
                $where[]=['p.name','like','%'.$param['pName'].'%'];
            }
            $rows = empty($param['limit']) ? get_config('app.page_size') : $param['limit'];
            $list=Db::name('sale_contract_detail')
                ->alias('scd')
                ->leftJoin('sale_contract sc','sc.id=scd.orderId')
                ->leftJoin('purveyor p','p.id=sc.punterId')
                ->where($where)
                ->field('scd.*,sc.orderNum as htNum,p.name as pName')
                ->paginate($rows);

            return table_assign(0,'获取成功',$list);
        }else{

            View::assign('type',$type);
            return  view('buy_invoice/addHt');
        }

}

    /**
     * @autho:xiangzi
     * @auth:true
     * @Date:2025/6/12
     * 采购付款单明细表获取合同明细
     */
    public function getCgHtMx()
    {
        $param=$this->request->param();
        $punterId=$param['punterId']??'';
        $mxId=$param['mxIds']??'';
        if ($this->request->isPost()){
            $where[]=['scd.type','=',2];
            $where[]=['scd.status','=',4];
            $where[]=['scd.isCgfkSelected','=',2];
            $where[]=['sc.payStatus','<>',3];
            if (isset($param['htOrderNum'])&&$param['htOrderNum']){
                $where[]=['sc.orderNum','like','%'.$param['htOrderNum'].'%'];
            }
            if (isset($param['mxIds'])&&$param['mxIds']){
                $where[]=['scd.id','not in',$param['mxIds']];
            }
            if (isset($param['punterId'])&&$param['punterId']){
                $where[]=['sc.punterId','=',$param['punterId']];
            }
            foreach (["buyCode","name","specs","brand"] as $v){
                if (isset($param[$v])&&$param[$v]){
                    $where[]=['md.'.$v,'like','%'.$param[$v].'%'];
                }
            }
            $rows = empty($param['limit']) ? get_config('app.page_size') : $param['limit'];

            $list=Db::name('sale_contract_detail')
                ->alias('scd')
                ->where($where)
                ->leftJoin('sale_contract sc','sc.id=scd.orderId')
                ->leftJoin('material_dossier md','md.id=scd.mdId')
                ->field('sc.orderNum as htNum,scd.*,md.brand,md.name as mdName,md.specs,md.buyCode,md.unit,scd.bjNum,scd.bjPrice')
                ->paginate($rows)->each(function ($item){
                    $dhNum=Db::name('stock_order_detail')
                        ->where('status',2)
                        ->where('type',3)
                        ->where('saleContractDetailId',$item['id'])->sum('num');
                    $dhMoney=$item['bjPrice']*$dhNum;
                    $dhPayed=Db::name('money_order_contract_detail')
                        ->where('status',2)
                        ->where('type',3)
                        ->where('contractMxId',$item['id'])
                        ->sum('money');

                    $item['dhMoney']=round($dhMoney,2);
                    $dhUnpayMoney=$dhMoney-$dhPayed;
                    $item['dhUnpayMoney']=$dhUnpayMoney<0?0:round($dhUnpayMoney,2);
                    $item['payedMoney']=round($dhPayed,2);
                    $item['unPayMoney']=round($item['bjMoney']-$dhPayed,2);
                    return $item;
                });
            return table_assign(0,'获取成功',$list);
        }else{
            View::assign(['punterId'=>$punterId,'mxIds'=>$mxId]);

            return view('purchase_payment/mx');
        }
}

    /**
     * @autho:xiangzi
     * @auth true
     * @Date:2025/6/20
     * 获取销售收款单
     */
    public function getSaleReceipt()
    {
        $param=$this->request->param();
        $punterId=$param['punterId'];
        if (!$punterId){
            return to_assign(1,'参数有误');
        }
        $list=Db::name('money_order')
            ->where('type',1)
            ->where('status',2)
            ->where('purveyorId',$punterId)
            ->field('orderNum,id')->select();

        return to_assign(0,'操作成功',$list);
}

    public function getSaleReceiptInfo()
    {
        $param=$this->request->param();
        $id=$param['id'];
        if (!$id){
            return to_assign(1,'参数有误');
        }
        $info=Db::name('money_order')->where('id',$id)
            ->where('status',2)->find();
        if (!$info){
            return to_assign(1,'参数有误');
        }
        $refunded=Db::name('money_order')->where('saveOrderId',$id)
            ->where('status',2)->sum('money');
        $info['refunded']=$refunded??0;
        $canRefund=$info['money']-$info['contactMoney']- $info['refunded'];
        $info['canRefund']=$canRefund;
         return to_assign(0,'操作成功',$info);
}

    /**
     * @autho:xiangzi
     * @auth true
     * @Date:2025/10/17
     * 获取客户/供应商详情
     */
    public function getPurveyorInfo()
    {
        $param=$this->request->param();
        $id=$param['id']??[];
        if (!$id){
            return to_assign(1,'参数缺失');
        }
        $info=Db::name('purveyor')->where('id',$id)->find();

        return to_assign(0,'获取成功',$info);

}
}
